<template>
	<div class="singleFile">
		<el-upload
			:action="oss.action"
			:data="oss"
			list-type="picture"
			:multiple="false"
			:show-file-list="showFileList"
			:file-list="fileList"
			:before-upload="beforeUpload"
			:on-remove="handleRemove"
			:on-success="handleSuccess"
			:on-preview="handlePreview"
		>
			<el-button size="small" type="primary">点击上传</el-button>
			<div slot="tip" class="el-upload__tip">上传文件，不超过10MB</div>
		</el-upload>
		<div>
			<el-dialog :visible.sync="dialog.visible"><img width="100%" :src="fileList[0].url" alt="" /></el-dialog>
		</div>
	</div>
</template>

<script>
export default {
	props: {
		url: { type: String, default: '' },
		dir: { type: String, default: '' }
	},
	computed: {
		fileList() {
			return [{ name: this.img.name, url: this.img.url }];
		},
		showFileList: {
			get: function() {
				let url_ = this.img.url;
				return url_ !== null && url_ !== '' && url_ !== undefined;
			},
			set: function(newVal) {}
		}
	},
	watch: {
		url: {
			handler() {
				this.img.url = this.url;
				if (this.url !== null && this.url !== '') {
					this.img.name = this.url.substring(this.url.lastIndexOf('/') + 1);
				}
			},
			immediate: true
		}
	},
	data() {
		return {
			dialog: {
				visible: false
			},
			oss: {
				policy: '',
				signature: '',
				key: '',
				OSSAccessKeyId: '',
				action: '',
				success_action_status: 200
			},
			img: {
				name: '',
				url: ''
			}
		};
	},
	methods: {
		emitSetUrl(val) {
			this.$emit('setUrl', val);
		},
		async beforeUpload(file) {
			let this_ = this;
			await this.$https.get('/file/getPolicyUploadInfo', { dir: this_.dir }).then(res => {
				this_.oss.key = this_.dir + '/' + new Date().getTime() + file.name;
				this_.oss.policy = res.data.data.policy;
				this_.oss.OSSAccessKeyId = res.data.data.accessid;
				this_.oss.signature = res.data.data.signature;
				this_.oss.action = res.data.data.host;
			});
		},
		handleRemove(file, fileList) {
			let this_ = this;
			this_.img.name = '';
			this_.img.url = '';
			this_.emitSetUrl('');
		},
		handleChange(file, fileList) {
			
		},
		handleSuccess(res, file, files) {
			let this_ = this;
			this_.img.name = file.name;
			this_.img.url = this_.oss.action + '/' + this_.oss.key;
			this_.emitSetUrl(this_.img.url);
			this_.$message.success('上传成功');
		},
		handlePreview(file) {
			this.dialog.visible = true;
		}
	}
};
</script>

<style></style>
